package com.yami.shop.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.yami.shop.bean.model.MeltCloudGroup;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.util.OssMultipartFile;
import com.yami.shop.common.util.PageUtil;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.dao.MeltCloudGroupMapper;
import com.yami.shop.service.AttachFileService;
import com.yami.shop.service.MeltCloudGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class MeltCloudGroupServiceImpl extends ServiceImpl<MeltCloudGroupMapper, MeltCloudGroup> implements MeltCloudGroupService {

    @Autowired
    private MeltCloudGroupMapper meltCloudGroupMapper;

    @Autowired
    private AttachFileService attachFileService;

    /**
     * 创建融云群组
     *
     * @param group
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertGroup(MeltCloudGroup group) {

        this.save(group);
        try{
            //生成二维码图片
            QrConfig config = new QrConfig(300,300);
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("content", group.getId());
            jsonObject.set("groupName",group.getGroupName());
            jsonObject.set("creatorUserId",group.getCreatorUserId());
            jsonObject.set("type",group.getType());
            BufferedImage qrgenerate = QrCodeUtil.generate(jsonObject.toString(), config);
            //保存图片
            ByteArrayOutputStream qrOutputStream = new ByteArrayOutputStream();
            //读文件
            ImageIO.write(qrgenerate,"jpg",qrOutputStream);
            MultipartFile ossMultipartFile = new OssMultipartFile("111.jpg", ".jpg", qrOutputStream.toByteArray());
            String fileName = attachFileService.uploadFile(ossMultipartFile.getBytes(), UUID.fastUUID()+".jpg");
            group.setGroupQrCode(fileName);
            this.updateById(group);
        }catch (Exception e){
            log.error("===创建群组异常{}",e);
        }
    }

    /**
     * 根据融云群组查询群组详细信息
     *
     * @param groupId
     * @return
     */
    @Override
    public List<MeltCloudGroup> list(List<Long> groupId) {
        LambdaQueryWrapper<MeltCloudGroup> wrapper = new LambdaQueryWrapper<MeltCloudGroup>()
                .in(MeltCloudGroup::getId, groupId);
        return this.list(wrapper);
    }

    /**
     * 获取所有群组接口
     *
     * @param pageDTO
     * @param param
     * @return
     */
    @Override
    public PageVO<MeltCloudGroup> getAll(PageDTO pageDTO, MeltCloudGroup param) {
        LambdaQueryWrapper<MeltCloudGroup> queryWrapper = new LambdaQueryWrapper<MeltCloudGroup>()
                .like(StrUtil.isNotEmpty(param.getGroupName()), MeltCloudGroup::getGroupName, param.getGroupName());
        if (Objects.nonNull(param.getShopId())) {
            queryWrapper.eq(MeltCloudGroup::getShopId, param.getShopId());
        }
        if (Objects.nonNull(param.getIsArrears())) {
            queryWrapper.eq(MeltCloudGroup::getIsArrears, param.getIsArrears());
        }
        if (StringUtils.isNotEmpty(param.getType())) {
            queryWrapper.eq(MeltCloudGroup::getType, param.getType());
        }
        if (Objects.nonNull(param.getIsOfficial())) {
            queryWrapper.eq(MeltCloudGroup::getIsOfficial, param.getIsOfficial());
        }
        if (StringUtils.isNotEmpty(param.getGroupStatus())) {
            queryWrapper.eq(MeltCloudGroup::getGroupStatus, param.getGroupStatus());
        }
        if (StringUtils.isNotEmpty(param.getIsDismiss())) {
            queryWrapper.eq(MeltCloudGroup::getIsDismiss, param.getIsDismiss());
        }
        queryWrapper.orderByDesc(MeltCloudGroup::getCreateDate);
        return PageUtil.doPage(pageDTO, () -> this.list(queryWrapper));
    }

    @Override
    public IPage<MeltCloudGroup> searchGroupListPage(Page page, String currentId, String groupName) {
        return meltCloudGroupMapper.searchGroupListPage(page, currentId, groupName);
    }

    @Override
    public com.alibaba.fastjson.JSONObject discernCodeByUrl(String path) {
        /**
         * 解析二维码,此方法解析一个路径的二维码图片
         * path:图片路径
         */
        String content = null;
        BufferedImage image;
        try {
            URL url = new URL(path);
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(urlConnection.getInputStream());
            image = ImageIO.read(bufferedInputStream);
            if(Objects.isNull(image)){
                com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
                return json;
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
            content = result.getText();
        } catch (IOException e) {
            e.printStackTrace();
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            return json;
        } catch (NotFoundException e) {
            //这里判断如果识别不了带LOGO的图片，重新添加上一个属性
            try {
                image = ImageIO.read(new File(path));
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                Binarizer binarizer = new HybridBinarizer(source);
                BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
                Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
                //设置编码格式
                hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
                //设置优化精度
                hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
                //设置复杂模式开启（我使用这种方式就可以识别微信的二维码了）
                hints.put(DecodeHintType.PURE_BARCODE,Boolean.TYPE);
                Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
                System.out.println("图片中内容：  ");
                System.out.println("content： " + result.getText());
                content = result.getText();
            } catch (IOException es) {
                es.printStackTrace();
                com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
                return json;
            } catch (NotFoundException eq) {
                eq.printStackTrace();
                com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
                return json;
            }
        }
        try{
            if(content.contains("http")){
                com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
                json.put("url",content);
                return json;
            }else{
                com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(content);
                return json;
            }
        }catch (Exception ex){
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            return json;
        }
    }


    @Override
    public List<MeltCloudGroup> ordinaryGroupPics(List<Long> ordinaryGroupIds) {
        List<MeltCloudGroup> list = meltCloudGroupMapper.ordinaryGroupPics(ordinaryGroupIds);
        return list;
    }


    @Override
    public List<MeltCloudGroup> dueSoonUltraGroup() {
        return meltCloudGroupMapper.dueSoonUltraGroup();
    }
    
    
}
